package com.zh.common.encryption;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import com.bumptech.glide.signature.ObjectKey;

import java.io.InputStream;

/**
 * Glide加载AES加密的网络图片
 * Glide.with(context).load(new MyDptFile(imageFile)).placeholder(R.drawable.common_placeholder).into(imageView);
 * https://blog.csdn.net/kuigu7110/article/details/118996102
 */
public class DptModelLoader implements ModelLoader<MyDptFile, InputStream> {

    private static final String TAG = "mylog_DptModelLoader";

    @Nullable
    @Override
    public LoadData<InputStream> buildLoadData(@NonNull MyDptFile myDptFile, int width, int height, @NonNull Options options) {
        Log.i(TAG, "buildLoadData：" + myDptFile.getFile().getAbsolutePath());
        return new LoadData(new ObjectKey(myDptFile), new DptModelLoader.DPtDataFetcher(myDptFile));
    }

    @Override
    public boolean handles(@NonNull MyDptFile myDptFile) {
        return true;
    }

    public static class DptLoaderFactory implements ModelLoaderFactory<MyDptFile, InputStream> {

        @NonNull
        @Override
        public ModelLoader<MyDptFile, InputStream> build(@NonNull MultiModelLoaderFactory multiFactory) {
            return new DptModelLoader();
        }

        @Override
        public void teardown() {
        }
    }

    public static class DPtDataFetcher implements DataFetcher<InputStream> {
        private MyDptFile file;

        public DPtDataFetcher(MyDptFile file) {
            this.file = file;
        }

        @Override
        public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super InputStream> callback) {
            Log.i(TAG, "图片解密--1, file= " + file.getFile().getAbsolutePath());
            if (file == null) {
                return;
            }
            //读取文件流，直接把文件流AES解密
            callback.onDataReady(CXAESUtil.decryptFileToInputStream(file.getFile(), CXAESUtil.AES_KEY));
        }

        /**
         * 这里是用来释放IO流的
         */
        @Override
        public void cleanup() {

        }

        @Override
        public void cancel() {

        }

        @NonNull
        @Override
        public Class<InputStream> getDataClass() {
            return InputStream.class;
        }

        @NonNull
        @Override
        public DataSource getDataSource() {
            return DataSource.LOCAL;
        }
    }
}
